import 'package:abc/controller/point_task_controller.dart';
import 'package:abc/model/point_model.dart';
import 'package:abc/page/point_record_page.dart';
import 'package:abc/view/CustomAppBar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class PointTaskPage extends GetView<PointTaskController> {
  const PointTaskPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (!Get.isRegistered<PointTaskController>()) {
      Get.lazyPut(() => PointTaskController());
    }
    return Scaffold(
      body: Stack(
        children: [
          Container(
            width: double.infinity,
            height: 316,
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Color(0xFFFA6A11),
                  Color(0xFFE17234),
                  Color(0xFFFFFFFF),
                ],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
              ),
            ),
          ),
          Positioned(
            top: 93,
            right: 0,
            child: Image.asset('assets/images/point_top_bg.png', height: 186),
          ),
          Column(
            children: [
              CustomAppBar(
                title: "积分任务",
                onBack: () {
                  Get.back();
                },
                rightText: "积分记录", // 添加右上角积分记录按钮
                onRightTextTap: () {
                  Get.to(() => const PointRecordPage()); // 跳转到积分记录页面
                },
              ),
              const SizedBox(height: 47),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildHeaderUserInfo(),
                  const SizedBox(height: 48),
                  Container(
                    width: double.infinity,
                    height: 380,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10.0),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          blurRadius: 10,
                          offset: const Offset(0, 5),
                        ),
                      ],
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          height: 34,
                          decoration: BoxDecoration(
                            color: Color(0xFFF5F5F5),
                            borderRadius: BorderRadius.circular(4),
                          ),
                          width: 157,
                          child: Obx(
                            () => TabBar(
                              dividerHeight: 0,
                              indicatorColor: Colors.transparent,
                              labelPadding: EdgeInsets.zero,
                              padding: EdgeInsets.all(0),
                              controller: controller.tabController,
                              labelColor: Colors.white,
                              unselectedLabelColor: Color(0XFF999999),
                              tabs: controller.tabs.asMap().entries.map((
                                entry,
                              ) {
                                int index = entry.key;
                                String tab = entry.value;
                                bool isSelected =
                                    controller.selectedIndex.value == index;

                                return Tab(
                                  child: Container(
                                    height: 34,
                                    decoration: BoxDecoration(
                                      gradient: LinearGradient(
                                        begin: Alignment.topCenter,
                                        end: Alignment.bottomCenter,
                                        colors: isSelected
                                            ? [
                                                Color(0xFFA877F4),
                                                Color(0xFF5650D6),
                                              ]
                                            : [
                                                Color(0xFFF5F5F5),
                                                Color(0xFFF5F5F5),
                                              ],
                                      ),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 8,
                                    ),
                                    child: Center(
                                      child: Text(
                                        tab,
                                        style: TextStyle(
                                          fontSize: 14,
                                          fontWeight: isSelected
                                              ? FontWeight.bold
                                              : FontWeight.normal,
                                          color: isSelected
                                              ? Colors.white
                                              : Color(0XFF999999),
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                          ),
                        ).paddingOnly(top: 18, left: 10),
                        Expanded(
                          child: TabBarView(
                            controller: controller.tabController,
                            children: <Widget>[
                              _buildTaskListView(), // 积分任务列表
                              _buildProductListView(), // 积分商城列表
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 20),
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10.0),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          blurRadius: 10,
                          offset: const Offset(0, 5),
                        ),
                      ],
                    ),
                    //  child: _buildRewardStats(),
                  ),
                  const SizedBox(height: 40),
                ],
              ).paddingSymmetric(horizontal: 16),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildHeaderUserInfo() {
    return Obx(
      () => Row(
        children: [
          Image.asset(
            'assets/images/ic_default_header.png',
            width: 40,
            height: 40,
          ),
          const SizedBox(width: 10),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                controller.userInfo.value.name,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.0,
                  fontWeight: FontWeight.w500,
                ),
              ),

              Row(
                children: [
                  const Text(
                    '剩余积分 ',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  Text(
                    controller.userInfo.value.points.toString(),
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 积分任务列表视图 (Tab 1)
  Widget _buildTaskListView() {
    return Obx(
      () => ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: controller.taskList.length,
        itemBuilder: (context, index) {
          final task = controller.taskList[index];
          return _buildTaskItem(task);
        },
      ),
    );
  }

  // 积分商城列表视图 (Tab 2)
  Widget _buildProductListView() {
    return Obx(
      () => ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: controller.productList.length,
        itemBuilder: (context, index) {
          final product = controller.productList[index];
          return _buildProductItem(product);
        },
      ),
    );
  }

  // 构建单个任务项
  Widget _buildTaskItem(PointTask task) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 14),
      child: Row(
        children: [
          Image.asset('assets/images/${task.icon}.png', width: 52, height: 52),
          const SizedBox(width: 15),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      task.title,
                      style: const TextStyle(
                        fontSize: 15,
                        color: Color(0xFF333333),
                      ),
                    ),
                    const SizedBox(width: 5),
                    Text(
                      task.subtitle,
                      style: const TextStyle(
                        fontSize: 13,
                        color: Color(0xFF333333),
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Text(
                      '奖励 ',
                      style: const TextStyle(
                        fontSize: 13,
                        color: Color(0xFF999999),
                      ),
                    ),
                    Text(
                      task.reward,
                      style: const TextStyle(
                        fontSize: 13,
                        color: Color(0xFF333333),
                      ),
                    ),
                    Text(
                      ' 积分',
                      style: const TextStyle(
                        fontSize: 13,
                        color: Color(0xFF999999),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          _buildActionButton(task.buttonText, task.isCompleted),
        ],
      ),
    );
  }

  // 构建单个商品项
  Widget _buildProductItem(PointProduct product) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 14),

      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      product.title,
                      style: const TextStyle(
                        fontSize: 18,
                        color: Color(0xFF333333),
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const SizedBox(width: 5),
                    Text(
                      product.subtitle,
                      style: const TextStyle(
                        fontSize: 13,
                        color: Color(0xFF333333),
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    // 使用RichText显示积分成本，将数字部分用黑色显示，其余部分用灰色显示
                    RichText(
                      text: TextSpan(
                        children: _buildPointsCostText(product.pointsCost),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          _buildActionButton(product.buttonText, product.isRedeemed),
        ],
      ),
    );
  }

  // 按钮封装
  Widget _buildActionButton(String text, bool completed) {
    if (completed || text == '已领取') {
      return Container(
        width: 70,
        height: 30,
        decoration: BoxDecoration(
          color: Color(0xFFF5F5F5),
          borderRadius: BorderRadius.circular(20),
        ),
        child: Center(
          child: Text(
            text,
            style: const TextStyle(color: Color(0xFFB3B3B3), fontSize: 12),
          ),
        ),
      );
    }
    return ElevatedButton(
      onPressed: () {},
      style: ElevatedButton.styleFrom(
        backgroundColor: Colors.transparent,
        shadowColor: Colors.transparent,
        padding: EdgeInsets.zero,
      ),
      child: Ink(
        width: 70,
        height: 30,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFFA877F4), Color(0xFF5650D6)],
          ),
          borderRadius: BorderRadius.circular(20),
        ),
        child: Center(
          child: Text(
            text,
            style: TextStyle(color: Colors.white, fontSize: 12),
          ),
        ),
      ),
    );
  }

  // 构建积分成本文本，将数字部分用黑色显示，其余部分用灰色显示
  List<TextSpan> _buildPointsCostText(String pointsCost) {
    List<TextSpan> spans = [];

    // 使用正则表达式匹配数字部分
    RegExp regex = RegExp(r'(\d+)');
    Iterable<RegExpMatch> matches = regex.allMatches(pointsCost);

    if (matches.isEmpty) {
      // 如果没有找到数字，直接返回灰色文本
      spans.add(
        TextSpan(
          text: pointsCost,
          style: const TextStyle(fontSize: 13, color: Color(0xFF999999)),
        ),
      );
      return spans;
    }

    // 处理匹配到的数字
    int lastEnd = 0;
    for (var match in matches) {
      // 添加数字前面的文本（灰色）
      if (match.start > lastEnd) {
        spans.add(
          TextSpan(
            text: pointsCost.substring(lastEnd, match.start),
            style: const TextStyle(fontSize: 13, color: Color(0xFF999999)),
          ),
        );
      }

      // 添加数字部分（黑色）
      spans.add(
        TextSpan(
          text: match.group(0),
          style: const TextStyle(fontSize: 13, color: Color(0xFF333333)),
        ),
      );

      lastEnd = match.end;
    }

    // 添加最后剩余的文本（如果有）
    if (lastEnd < pointsCost.length) {
      spans.add(
        TextSpan(
          text: pointsCost.substring(lastEnd),
          style: const TextStyle(fontSize: 13, color: Color(0xFF999999)),
        ),
      );
    }

    return spans;
  }
}

// --- SliverPersistentHeaderDelegate 用于固定 TabBar ---
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar _tabBar;

  _SliverAppBarDelegate(this._tabBar);

  @override
  double get minExtent => _tabBar.preferredSize.height;
  @override
  double get maxExtent => _tabBar.preferredSize.height;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Container(
      // TabBar 的背景色设置为白色
      color: Colors.white,
      child: _tabBar,
    );
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return false;
  }
}
